<?php

namespace App\Http\Controllers\Api\Third;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\ContractGaiyaoController;
use Illuminate\Support\Facades\Storage;
use DB;

//山东带电作业内网接口
class NxndApiController extends Controller
{
    // 1、服务器地址:
    private $BaseUrl = "http://ip:port/";

    public function __construct($BaseUrl){
        $this->BaseUrl = $BaseUrl;
    }

    //2、获取待检工具项目信息
    public function getGqjBookTestInfo($thirdMap){
        $thirdId = request('third_id',0);
        //$url = $this->BaseUrl.'/api/testdata/toolinfos';
        $url = $this->BaseUrl;
        $postData = request('thirdParams',[]);
        $postData = json_encode($postData);
        if (isAdmin()) {
            $res = file_get_contents('./ddzy.json');
            $res =  str_replace(["\r\n",' '],'',$res);
            $res = json_decode($res,true);
        }else{
            $res = json_decode(curl($url, $postData),true);
        }
        info('NxndApiController');
        info($res);
        if (!$res['successful']) {
            info('NxndApiController-获取数据失败');
            return '获取数据失败！';
        }
        echo '<pre>';
        var_dump($res);
        die;

        $data = $res['data'];
        //将每个工器具的数据进行分析汇总 start
        $data2 = [];
        foreach ($data as $item) {
            $rfid = $item['rfid'];
            $data2[$item['categoryName']][$item['standardCode']][$item['voltageName']]["{$rfid}"][] = $item;
        }

        // dd($data2);
        //将每个工器具的数据进行分析汇总 end
        $gaiyaos = [];
        $total = 0;

        foreach ($data2 as $toolName => $iTool) {
            // 0：额定电压；1：分类；2：工器具；3：检测标准；4：检测项目；5：检测数据
            //判断工器具类型是否对照，没有对照报错提醒
            if (!isset($thirdMap[2]['third'][$toolName])) {
                return "工器具类型：{$toolName} 缺少映射关系！";
            }

            $tool_id = $thirdMap[2]['third'][$toolName]['sys_id'];   //a_tool 工器具表中该工器具的id
            foreach($iTool as $stdNum => $iStd){
                //判断检测标准是否对照，没有对照报错提醒
                if (!isset($thirdMap[3]['third'][$stdNum])) {
                    return "检测标准：{$stdNum} 缺少映射关系！";
                }
                $std_id = $thirdMap[3]['third'][$stdNum]['sys_id']; //a_standard 检测标准表中的标准id
                foreach($iStd as $voltage => $iVol){
                    //判断检测标准是否对照，没有对照报错提醒
                    if (!isset($thirdMap[0]['third'][$voltage])) {
                        return "额定电压：{$voltage} 缺少映射关系！";
                    }

                     //dd($thirdMap[0]['third'][$voltage]['sys_name'],$std_id,$tool_id);
                    $vol_id = DB::table('a_voltage_class')
                            ->where([
                                    'std_id'=>$std_id,
                                    'tool_id'=>$tool_id,
                                    'val'=>$thirdMap[0]['third'][$voltage]['sys_name'],
                                    'type'=>0,
                                ])
                            ->value('id');//获取工器具在检测标准下的额定电压
                    if (!$vol_id) {
                        return $thirdMap[2]['third'][$toolName]['sys_name'].' '.$thirdMap[3]['third'][$stdNum]['sys_name'].' '.'不存在'.$thirdMap[0]['third'][$voltage]['sys_name'].'的额定电压';
                    }

                    $class_id = 0; //未指定
                    $sysItemIds = DB::table('a_std_tool_item_rel')->where(['std_id'=>$std_id,'tool_id'=>$tool_id])->pluck('testitem_id')->toArray();
                    foreach ($iVol as $PcRfid => $item) {
                        // dd($thirdMap[4]['third']);
                        //判断检测项目是否对照，没有对照报错提醒
                        $itemIds = [];
                        $item_ids_str = '';
                        foreach ($item as $itemItem) {
                            echo '<pre>';
                            var_dump($itemItem);
                            echo '</pre>';
                            echo '<hr/>';
                            if(!isset($thirdMap[4]['third'][$itemItem['projectTypeName']])){
                                return '检测项目：'.$itemItem['projectTypeName'].' 缺少映射关系！';
                            }
                            $itemId = 0;
                            $itemMaps = $thirdMap[4]['third'][$itemItem['projectTypeName']];
                            foreach ($itemMaps as $itemMap) {
                                echo '<pre>';
                                var_dump($itemMap);
                                if (in_array($itemMap['sys_id'],$sysItemIds)) { //有异议
                                    $itemId = $itemIds[] = $itemMap['sys_id'];
                                    continue;
                                }
                            }
                            if ($itemId === 0) {
                                return '检测项目：'.$itemItem['projectTypeName'].' 缺少指定映射！';
                            }
                        }

                        $item_ids_str = implode(',',$itemIds);
                        //如果样品已存在，继续下一个
                        list($thirdPcId,$rfid) = explode('][',$PcRfid);

                        //判断没有退样的批次中是否存在该样品
                        $exists = DB::table('a_contract_gaiyao as a')
                                ->leftJoin('a_sample_info as b','a.id','=','b.contract_gaiyao_id')
                                ->leftJoin('a_contract as c','a.contract_id','=','c.id')
                                ->where([
                                        ['a.third_id','=',$thirdId],
                                        ['b.third_id','=',$rfid],
                                        ['b.third_contract_id','=',$thirdPcId],
                                        ['c.status','<',20]
                                    ])
                                ->exists();
                        if($exists){
                            continue;
                        }
                        $gaiyaos["{$tool_id}][{$std_id}][{$vol_id}][{$class_id}][{$item_ids_str}"][] = [$thirdPcId,$rfid];
                        $total += 1;
                    }
                }
            }

        }
         dd($gaiyaos);
        if (!$gaiyaos) {
            return '上传样品均在受理中！';
        }

        $gaiyaoCon = new ContractGaiyaoController();
        DB::beginTransaction();
        try{
            foreach($gaiyaos as $key => $PcRfids){
                $count = count($PcRfids);
                list($tool_id,$std_id,$vol_id,$class_id,$item_ids_str) = explode('][',$key);
                request()->offsetSet('tool_id',$tool_id);
                request()->offsetSet('std_id',$std_id);
                request()->offsetSet('vol_id',$vol_id);
                request()->offsetSet('class_id',$class_id);
                request()->offsetSet('items',explode(',',$item_ids_str));
                request()->offsetSet('count',$count);
                // request()->offsetSet('remark','带电作业系统导入数据');
                $gyId = $gaiyaoCon->add();
                $samples = DB::table('a_sample_info')->where('contract_gaiyao_id',$gyId)->get();
                foreach ($samples as $k => $sample) {
                    list($thirdPcId,$rfid) = $PcRfids[$k];
                    DB::table('a_sample_info')->where('id',$sample->id)->update(['third_id'=>$rfid,'third_contract_id'=>$thirdPcId]);
                }
            }
            DB::commit();
        }catch(\Exception $e){
            DB::rollBack();
            return "导入失败：".$e->getLine().$e->getMessage();
        }
        return $total;
    }

    //3、提交待检工具试验信息，跟客户沟通 通过 批次id，RFID，项目id 传数据
    public function saveGqjBookTestInfo($thirdMap){
        $testList = [];
        // $testList = "[{
            // 'testId':'1',
            // 'rfid':'1',
            // 'projectTypeId':'0',
            // 'isPass':true,
            // 'testValue':'1',
            // 'duration':0,0
            // 'pressurizationTimes':0,
            // 'leakageVotage':0,   //未知
            // 'leakageCurrent':0,
            // 'leakageTime':0,
            // 'sectionalArea':0,
            // 'shielding':0,
            // 'speed':0,
        // }]";
        // dd($inputDatas);
        foreach($inputDatas as $input){
            if ($input->third_key) {
                if (!isset($testList[$input->item_id])) {
                    $testList[$input->item_id]['testId'] = $input->third_contract_id; //带电作业系统工单id
                    $testList[$input->item_id]['rfid'] = $input->third_id; //带电作业系统样品rfid
                    $testList[$input->item_id]['projectTypeId'] = $input->third_pro_type_id; //带电作业系统项目id
                    $res = $input->sys_item_res;
                    $testList[$input->item_id]['isPass'] = ($res==1 ? true : ($res==0 ? false : null)); //判定项目结论
                }
                $bei = $input->bei ?: 1;
                $testList[$input->item_id][$input->third_key] = (floatval($input->val) * $bei) ?: 0;
            }
        }
        sort($testList);
        // dd($testList);
        $url = $this->BaseUrl.'/api/testdata/submitinfo';
        $postData = json_encode($testList);
        return curl($url, $postData);
    }

    //4、试验类型(项目)、试验数据对照表
    public function getTestItems(){
        //$ary下标是试验类型id：projectTypeId
        $ary = [
            '01'=>[
                'name'=>'表面工频耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '02'=>[
                'name'=>'操作冲击耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'pressurizationTimes'=>'加压次数',
                ]
            ],
            '03'=>[
                'name'=>'成组直流电阻试验',
                'upload'=>[
                    'sectionalArea'=>'截面积mm²',
                    'testValue'=>'电阻mΩ',
                ]
            ],
            '04'=>[
                'name'=>'冲击性能试验',
                'upload'=>[
                    'testValue'=>'冲击力N',
                ]
            ],
            '05'=>[
                'name'=>'电阻试验和屏蔽效率试验',
                'upload'=>[
                    'testValue'=>'电阻mΩ',
                    'shielding'=>'屏蔽效率dB',
                ]
            ],
            '06'=>[
                'name'=>'复合气瓶检查',
                'upload'=>[
                    'testValue'=>'压力%',
                    'duration'=>'时长s',
                ]
            ],
            '08'=>[
                'name'=>'工频耐压及泄漏电流试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                    'leakageCurrent'=>'泄漏电流mA',
                ]
            ],
            '09'=>[
                'name'=>'工频耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '11'=>[
                'name'=>'静负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '12'=>[
                'name'=>'静抗弯负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '13'=>[
                'name'=>'绝缘强度试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
            '14'=>[
                'name'=>'空载动作冲击性能试验',
                'upload'=>[]
            ],
            '17'=>[
                'name'=>'屏蔽效率试验',
                'upload'=>[
                    'duration'=>'时长s',
                    'shielding'=>'屏蔽效率dB',
                ]
            ],
            '18'=>[
                'name'=>'启动电压试验',
                'upload'=>[
                    'testValue'=>'启动电压kV',
                ]
            ],
            '19'=>[
                'name'=>'泄漏电流试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                    'leakageCurrent'=>'泄漏电流mA',
                ]
            ],
            '20'=>[
                'name'=>'整体静负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '21'=>[
                'name'=>'直流电阻试验',
                'upload'=>[
                    'testValue'=>'电阻mΩ',
                ]
            ],
            '22'=>[
                'name'=>'动负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'pressurizationTimes'=>'试验次数',
                ]
            ],
            '23'=>[
                'name'=>'动抗弯负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '25'=>[
                'name'=>'静抗扭负荷试验',
                'upload'=>[
                    'testValue'=>'荷载N',
                    'duration'=>'时长s',
                ]
            ],
            '26'=>[
                'name'=>'压力与流量试验',
                'upload'=>[
                    'testValue'=>'压力kPa',
                    'Speed'=>'流量L/min',
                ]
            ],
            '27'=>[
                'name'=>'整组试验',
                'upload'=>[
                    'testValue'=>'水柱长度cm',
                ]
            ],
            '28'=>[
                'name'=>'直流耐压试验',
                'upload'=>[
                    'testValue'=>'耐压kV',
                    'duration'=>'时长s',
                ]
            ],
        ];
        return $ary;
    }

    // 5、获取基础数据信息 type:类型 1 工具分类  2 电压等级
    public function getTools($type=1){
        $url = $this->BaseUrl.'/api/testdata/getbaseitems';
        $postData = [
            'type'=>$type,
        ];
        $postData = json_encode($postData);
        $res = deCurl($url, $postData);
        if ($res['statusCode'] == 200 && $res['successed'] === true) {
            return $res['data'];
        }
    }
}
